<template>
  <div class="app-container">
    <el-card class="common-card query-box">
      <div class="queryForm">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
          <el-form-item :label="$t('merchantProduct.merchantName')" prop="merchantName">
            <el-input
                v-model="queryParams.merchantName"
                :placeholder="$t('merchantProduct.merchantNamePlaceholder')"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('merchantProduct.productName')" prop="productName">
            <el-input
                v-model="queryParams.productName"
                :placeholder="$t('merchantProduct.productNamePlaceholder')"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('merchantProduct.status')" prop="status">
            <el-select
                v-model="queryParams.status"
                :placeholder="$t('merchantProduct.statusPlaceholder')"
                clearable
                style="width: 200px"
            >
              <el-option
                  v-for="dict in sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">{{ $t('jbx.text.query') }}</el-button>
            <el-button @click="resetQuery">{{ $t('jbx.text.reset') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="common-card">
      <div class="btn-form">
        <el-button type="primary" @click="handleAdd">{{ $t('jbx.text.add') }}</el-button>
        <el-button @click="handleDeleteBatch" :disabled="ids.length === 0">{{ $t('jbx.text.deleteBatch') }}</el-button>
      </div>
      
      <el-table v-loading="loading" :data="merchantProductList" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column :label="$t('merchantProduct.id')" align="center" prop="id" />
        <el-table-column :label="$t('merchantProduct.merchantName')" align="center" prop="merchantName" />
        <el-table-column :label="$t('merchantProduct.productName')" align="center" prop="productName" />
        <el-table-column :label="$t('merchantProduct.productVersion')" align="center" prop="productVersion" />
        <el-table-column :label="$t('merchantProduct.licenseKey')" align="center" prop="licenseKey" />
        <el-table-column :label="$t('merchantProduct.startDate')" align="center" prop="startDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('merchantProduct.endDate')" align="center" prop="endDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('merchantProduct.maxUserCount')" align="center" prop="maxUserCount" />
        <el-table-column :label="$t('merchantProduct.status')" align="center" prop="status">
          <template #default="scope">
            <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column :label="$t('jbx.text.createdDate')" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('jbx.text.action')" align="center" width="140">
          <template #default="scope">
            <el-button icon="View" link @click="handleView(scope.row)"></el-button>
            <el-button icon="Edit" link @click="handleUpdate(scope.row)"></el-button>
            <el-button icon="Delete" link @click="handleDelete(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改商户产品对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="merchantProductRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('merchantProduct.merchantName')" prop="merchantId">
              <el-select 
                v-model="form.merchantId" 
                :placeholder="$t('merchantProduct.merchantNamePlaceholder')" 
                style="width: 100%"
                filterable
              >
                <el-option
                    v-for="merchant in merchantOptions"
                    :key="merchant.id"
                    :label="merchant.merchantName"
                    :value="merchant.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('merchantProduct.productName')" prop="productId">
              <el-select 
                v-model="form.productId" 
                :placeholder="$t('merchantProduct.productNamePlaceholder')" 
                style="width: 100%"
                filterable
              >
                <el-option
                    v-for="product in productOptions"
                    :key="product.id"
                    :label="product.productName"
                    :value="product.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('merchantProduct.startDate')" prop="startDate">
              <el-date-picker 
                  v-model="form.startDate" 
                  type="date" 
                  :placeholder="$t('merchantProduct.startDatePlaceholder')"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('merchantProduct.endDate')" prop="endDate">
              <el-date-picker 
                  v-model="form.endDate" 
                  type="date" 
                  :placeholder="$t('merchantProduct.endDatePlaceholder')"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item :label="$t('merchantProduct.licenseKey')" prop="licenseKey">
          <el-input v-model="form.licenseKey" :placeholder="$t('merchantProduct.licenseKeyPlaceholder')" />
        </el-form-item>
        <el-form-item :label="$t('merchantProduct.maxUserCount')" prop="maxUserCount">
          <el-input-number v-model="form.maxUserCount" controls-position="right" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item :label="$t('merchantProduct.status')">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">{{ $t('jbx.text.submit') }}</el-button>
          <el-button @click="cancel">{{ $t('jbx.text.close') }}</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 商户产品详情对话框 -->
    <el-dialog :title="detailTitle" v-model="openView" width="600px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item :label="$t('merchantProduct.merchantName')">{{ detailData.merchantName }}</el-descriptions-item>
        <el-descriptions-item :label="$t('merchantProduct.productName')">{{ detailData.productName }}</el-descriptions-item>
        <el-descriptions-item :label="$t('merchantProduct.productVersion')">{{ detailData.productVersion }}</el-descriptions-item>
        <el-descriptions-item :label="$t('merchantProduct.licenseKey')">{{ detailData.licenseKey }}</el-descriptions-item>
        <el-descriptions-item :label="$t('merchantProduct.startDate')">{{ parseTime(detailData.startDate) }}</el-descriptions-item>
        <el-descriptions-item :label="$t('merchantProduct.endDate')">{{ parseTime(detailData.endDate) }}</el-descriptions-item>
        <el-descriptions-item :label="$t('merchantProduct.maxUserCount')">{{ detailData.maxUserCount }}</el-descriptions-item>
        <el-descriptions-item :label="$t('merchantProduct.status')">
          <el-tag :type="detailData.status === 1 ? 'success' : 'danger'">
            {{ detailData.status === 1 ? $t('jbx.text.enable') : $t('jbx.text.disable') }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item :label="$t('jbx.text.createdDate')">{{ parseTime(detailData.createTime) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openView = false">{{ $t('jbx.text.close') }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MerchantProduct" lang="ts">
import { ref, getCurrentInstance, reactive, toRefs, nextTick } from "vue";
import { ElForm } from "element-plus";
import modal from "@/plugins/modal";
import { useI18n } from "vue-i18n";
import { parseTime } from "@/utils/Jinbooks";
import { 
  listMerchantProduct, 
  getMerchantProduct, 
  addMerchantProduct, 
  updateMerchantProduct, 
  delMerchantProduct,
  listMerchant,
  listProduct
} from "@/api/merchant/merchant-product";

const { t } = useI18n();
const { proxy } = getCurrentInstance()!;

// 字典数据
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

// 定义变量
const merchantProductList = ref([]);
const open = ref(false);
const openView = ref(false);
const loading = ref(true);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const detailTitle = ref("");
const ids = ref([]);
const merchantOptions = ref([]);
const productOptions = ref([]);
const detailData = ref({});

// 查询参数
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merchantName: undefined,
    productName: undefined,
    status: undefined
  },
  form: {
    id: undefined,
    merchantId: undefined,
    productId: undefined,
    startDate: undefined,
    endDate: undefined,
    licenseKey: undefined,
    maxUserCount: 0,
    status: 1
  },
  rules: {
    merchantId: [{ required: true, message: t('merchantProduct.merchantNameRequired'), trigger: "blur" }],
    productId: [{ required: true, message: t('merchantProduct.productNameRequired'), trigger: "blur" }],
    startDate: [{ required: true, message: t('merchantProduct.startDateRequired'), trigger: "blur" }],
    endDate: [{ required: true, message: t('merchantProduct.endDateRequired'), trigger: "blur" }],
    licenseKey: [{ required: true, message: t('merchantProduct.licenseKeyRequired'), trigger: "blur" }],
    maxUserCount: [{ required: true, message: t('merchantProduct.maxUserCountRequired'), trigger: "blur" }]
  }
});

const { queryParams, form, rules } = toRefs(data);
const queryRef = ref<InstanceType<typeof ElForm> | null>(null);
const merchantProductRef = ref<InstanceType<typeof ElForm> | null>(null);

// 获取列表
function getList() {
  loading.value = true;
  listMerchantProduct(queryParams.value).then(response => {
    merchantProductList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

// 获取商户和产品选项
function getOptions() {
  // 获取商户选项
  listMerchant().then(response => {
    merchantOptions.value = response.data.records;
  });
  
  // 获取产品选项
  listProduct().then(response => {
    productOptions.value = response.data.records;
  });
}

// 查询
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置
function resetQuery() {
  queryRef.value?.resetFields();
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 商户产品状态修改
function handleStatusChange(row) {
  let text = row.status === 1 ? t('jbx.text.enable') : t('jbx.text.disable');
  modal.confirm(t('jbx.confirm.text') + text + t('jbx.text.is') + t('merchantProduct.productName') + "“" + row.productName + "”？").then(function() {
    // 模拟修改状态
    modal.msgSuccess(t('jbx.alert.operate.success'));
    return Promise.resolve();
  }).catch(function() {
    row.status = row.status === 1 ? 0 : 1;
  });
}

// 新增
function handleAdd() {
  reset();
  open.value = true;
  title.value = t('merchantProduct.add');
  nextTick(() => {
    merchantProductRef.value?.clearValidate();
  });
}

// 修改
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value[0];
  getMerchantProduct(id).then(response => {
    let productData = response.data;
    // 处理日期格式
    if (productData.startDate) {
      productData.startDate = productData.startDate.split(' ')[0];
    }
    if (productData.endDate) {
      productData.endDate = productData.endDate.split(' ')[0];
    }
    form.value = productData;
    open.value = true;
    title.value = t('merchantProduct.edit');
  });
}

// 删除
function handleDelete(row) {
  const merchantProductIds = row.id || ids.value;
  modal.confirm(t('jbx.confirm.text.delete')).then(function() {
    return delMerchantProduct(merchantProductIds).then(() => {
      modal.msgSuccess(t('jbx.alert.delete.success'));
      getList();
    });
  }).catch(() => {});
}

// 批量删除
function handleDeleteBatch() {
  modal.confirm(t('jbx.confirm.text.delete')).then(function() {
    return delMerchantProduct(ids.value).then(() => {
      modal.msgSuccess(t('jbx.alert.delete.success'));
      getList();
    });
  }).catch(() => {});
}

// 查看详情
function handleView(row) {
  getMerchantProduct(row.id).then(response => {
    detailData.value = response.data;
    openView.value = true;
    detailTitle.value = t('merchantProduct.detail');
  });
}

// 提交表单
function submitForm() {
  merchantProductRef.value?.validate((valid) => {
    if (valid) {
      if (form.value.id) {
        // 修改操作
        updateMerchantProduct(form.value).then(response => {
          modal.msgSuccess(t('jbx.alert.update.success'));
          open.value = false;
          getList();
        });
      } else {
        // 新增操作
        addMerchantProduct(form.value).then(response => {
          modal.msgSuccess(t('jbx.alert.add.success'));
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 取消
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: undefined,
    merchantId: undefined,
    productId: undefined,
    startDate: undefined,
    endDate: undefined,
    licenseKey: undefined,
    maxUserCount: 0,
    status: 1
  };
  merchantProductRef.value?.resetFields();
}

// 初始化数据
getList();
getOptions();
</script>

<style scoped>
.common-card {
  margin-bottom: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.query-box {
  margin-bottom: 15px;
  border-radius: 8px;
  overflow: hidden;
}

.queryForm {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 15px;
  padding: 15px 0;
}

.btn-form {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>